#include "CTSBuilder.h"
#include <algorithm>

using namespace std;

CTSBuilder::CTSBuilder(std::set<unsigned int> pids) : m_nCurrentTsSize(0), m_pids(pids)
{
}

CTSBuilder::~CTSBuilder()
{
	for(unsigned int j=0; j<m_mTs.size(); j++)
		delete m_mTs[j];
}


void CTSBuilder::findTS(CESParser& cESParser){

	const char* cBuffer = cESParser.getData();
	int nSize = cESParser.getSize();

	int nPointer = 0;

	while (nSize > 0){
		int nReadBytes = _BuildTS(cBuffer + nPointer, nSize);
		nPointer += nReadBytes;
		nSize -= nReadBytes;
	}
}

int CTSBuilder::_BuildTS(const char* cBuffer, int nBufferSize){
	if (m_nCurrentTsSize > 0){
		int nCopy = min(nBufferSize, 188-m_nCurrentTsSize);
		memcpy(m_sLastTs+m_nCurrentTsSize,cBuffer,nCopy);
		if (m_nCurrentTsSize+ nCopy == 188){
			_add2List();
		}
		return nCopy;
	}

	int nPointer = 0;
	while (cBuffer[nPointer] != 0x47 && nPointer < nBufferSize){
		nPointer++;
	}
	if (nPointer >= nBufferSize)
		return nBufferSize;

	int nCopy = min(nBufferSize - nPointer, 188);
	memcpy((char*)m_sLastTs, cBuffer + nPointer, nCopy);
	if (nCopy == 188){
		_add2List();
	}
	return nPointer + nCopy;
}

void CTSBuilder::_add2List(){
	CTS* newTs = new CTS(m_sLastTs);
	m_nCurrentTsSize = 0;
	if ((m_pids.find(newTs->getPID())) != m_pids.end()){ 
		newTs->setError();
	}

	m_mTs.push_back(newTs);
}


